package com.xiaozhi.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaozhi.entity.HealthAnalytics;
import com.itheima.java.ai.langchin4j.entity.HealthRecord;
import com.itheima.java.ai.langchin4j.entity.VitalSigns;
import com.xiaozhi.mapper.HealthAnalyticsMapper;
import com.itheima.java.ai.langchin4j.mapper.HealthRecordMapper;
import com.itheima.java.ai.langchin4j.mapper.VitalSignsMapper;
import com.xiaozhi.service.HealthAnalyticsService;
import com.xiaozhi.utils.HealthAnalysisOptimizer;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 健康数据分析服务实现类
 *
 * @author xiaozhi
 * @since 2024-01-15
 */
@Service
public class HealthAnalyticsServiceImpl extends ServiceImpl<HealthAnalyticsMapper, HealthAnalytics> implements HealthAnalyticsService {

    private static final Logger log = LoggerFactory.getLogger(HealthAnalyticsServiceImpl.class);

    @Autowired
    private HealthAnalyticsMapper healthAnalyticsMapper;

    @Autowired
    private HealthRecordMapper healthRecordMapper;

    @Autowired
    private VitalSignsMapper vitalSignsMapper;
    
    @Autowired
    private HealthAnalysisOptimizer analysisOptimizer;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public HealthAnalytics generateHealthAnalysis(Long userId, String analysisType, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("开始生成健康分析，用户ID: {}, 分析类型: {}, 时间范围: {} - {}", userId, analysisType, startDate, endDate);
        
        try {
            HealthAnalytics analytics = new HealthAnalytics();
            analytics.setUserId(userId);
            analytics.setAnalysisType(analysisType);
            analytics.setStartDate(startDate);
            analytics.setEndDate(endDate);
            analytics.setStatus("PROCESSING");
            analytics.setIsRead(false);
            analytics.setAnalysisVersion("1.0");
            analytics.setDataSource("MIXED");
            
            // 根据分析类型生成相应的分析
            switch (analysisType) {
                case "VITAL_SIGNS":
                    return generateVitalSignsAnalysis(userId, startDate, endDate);
                case "HEALTH_TREND":
                    return generateHealthTrendAnalysis(userId, startDate, endDate);
                case "RISK_ASSESSMENT":
                    return generateRiskAssessment(userId, startDate, endDate);
                case "SYMPTOM_PATTERN":
                    return generateSymptomPatternAnalysis(userId, startDate, endDate);
                case "COMPREHENSIVE":
                    return generateComprehensiveAnalysis(userId, startDate, endDate);
                default:
                    throw new IllegalArgumentException("不支持的分析类型: " + analysisType);
            }
        } catch (Exception e) {
            log.error("生成健康分析失败", e);
            throw new RuntimeException("生成健康分析失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    @Cacheable(value = "vitalSigns", key = "#userId + '_' + #startDate + '_' + #endDate")
    public HealthAnalytics generateVitalSignsAnalysis(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("生成生命体征分析，用户ID: {}", userId);
        
        // 获取生命体征数据
        List<VitalSigns> vitalSignsList = vitalSignsMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        
        if (vitalSignsList.isEmpty()) {
            throw new RuntimeException("指定时间范围内没有生命体征数据");
        }
        
        // 使用优化的分析算法
        Map<String, Object> analysisData = analysisOptimizer.optimizedVitalSignsAnalysis(vitalSignsList);
        
        // 计算健康评分
        Integer healthScore = calculateVitalSignsScore(vitalSignsList);
        
        // 评估风险等级
        String riskLevel = assessVitalSignsRisk(analysisData, healthScore);
        
        // 生成分析摘要
        String summary = generateVitalSignsSummary(analysisData, healthScore, riskLevel);
        
        // 生成建议
        String recommendations = generateVitalSignsRecommendations(analysisData, riskLevel);
        
        // 检测异常指标
        List<String> abnormalIndicators = detectVitalSignsAbnormalities(vitalSignsList);
        
        // 分析趋势
        String trendDirection = analyzeVitalSignsTrend(vitalSignsList);
        
        // 创建分析记录
        HealthAnalytics analytics = new HealthAnalytics();
        analytics.setUserId(userId);
        analytics.setAnalysisType("VITAL_SIGNS");
        analytics.setStartDate(startDate);
        analytics.setEndDate(endDate);
        analytics.setHealthScore(healthScore);
        analytics.setRiskLevel(riskLevel);
        analytics.setSummary(summary);
        analytics.setRecommendations(recommendations);
        analytics.setTrendDirection(trendDirection);
        analytics.setStatus("COMPLETED");
        analytics.setIsRead(false);
        analytics.setAnalysisVersion("1.0");
        analytics.setDataSource("DEVICE");
        
        try {
            analytics.setAnalysisData(objectMapper.writeValueAsString(analysisData));
            analytics.setAbnormalIndicators(String.join(", ", abnormalIndicators));
        } catch (JsonProcessingException e) {
            log.error("序列化分析数据失败", e);
            throw new RuntimeException("序列化分析数据失败");
        }
        
        // 保存分析结果
        save(analytics);
        
        log.info("生命体征分析完成，分析ID: {}", analytics.getId());
        return analytics;
    }

    @Override
    @Transactional
    public HealthAnalytics generateHealthTrendAnalysis(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("生成健康趋势分析，用户ID: {}", userId);
        
        // 获取历史健康数据
        List<HealthRecord> healthRecords = healthRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        List<VitalSigns> vitalSignsList = vitalSignsMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        
        if (healthRecords.isEmpty() && vitalSignsList.isEmpty()) {
            throw new RuntimeException("指定时间范围内没有健康数据");
        }
        
        // 分析健康趋势
        Map<String, Object> analysisData = analyzeHealthTrend(healthRecords, vitalSignsList);
        
        // 计算健康评分
        Integer healthScore = calculateTrendScore(analysisData);
        
        // 评估风险等级
        String riskLevel = assessTrendRisk(analysisData, healthScore);
        
        // 生成分析摘要
        String summary = generateTrendSummary(analysisData, healthScore, riskLevel);
        
        // 生成建议
        String recommendations = generateTrendRecommendations(analysisData, riskLevel);
        
        // 分析趋势方向
        String trendDirection = analyzeTrendDirection(analysisData);
        
        // 创建分析记录
        HealthAnalytics analytics = new HealthAnalytics();
        analytics.setUserId(userId);
        analytics.setAnalysisType("HEALTH_TREND");
        analytics.setStartDate(startDate);
        analytics.setEndDate(endDate);
        analytics.setHealthScore(healthScore);
        analytics.setRiskLevel(riskLevel);
        analytics.setSummary(summary);
        analytics.setRecommendations(recommendations);
        analytics.setTrendDirection(trendDirection);
        analytics.setStatus("COMPLETED");
        analytics.setIsRead(false);
        analytics.setAnalysisVersion("1.0");
        analytics.setDataSource("MIXED");
        
        try {
            analytics.setAnalysisData(objectMapper.writeValueAsString(analysisData));
        } catch (JsonProcessingException e) {
            log.error("序列化分析数据失败", e);
            throw new RuntimeException("序列化分析数据失败");
        }
        
        // 保存分析结果
        save(analytics);
        
        log.info("健康趋势分析完成，分析ID: {}", analytics.getId());
        return analytics;
    }

    @Override
    @Transactional
    public HealthAnalytics generateRiskAssessment(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("生成风险评估分析，用户ID: {}", userId);
        
        // 获取用户健康数据
        List<HealthRecord> healthRecords = healthRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        List<VitalSigns> vitalSignsList = vitalSignsMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        
        // 进行风险评估
        Map<String, Object> analysisData = performRiskAssessment(userId, healthRecords, vitalSignsList);
        
        // 计算风险评分
        Integer healthScore = calculateRiskScore(analysisData);
        
        // 确定风险等级
        String riskLevel = determineRiskLevel(healthScore, analysisData);
        
        // 生成评估摘要
        String summary = generateRiskSummary(analysisData, healthScore, riskLevel);
        
        // 生成风险建议
        String recommendations = generateRiskRecommendations(analysisData, riskLevel);
        
        // 识别关键风险因素
        List<String> riskFactors = identifyRiskFactors(analysisData);
        
        // 创建分析记录
        HealthAnalytics analytics = new HealthAnalytics();
        analytics.setUserId(userId);
        analytics.setAnalysisType("RISK_ASSESSMENT");
        analytics.setStartDate(startDate);
        analytics.setEndDate(endDate);
        analytics.setHealthScore(healthScore);
        analytics.setRiskLevel(riskLevel);
        analytics.setSummary(summary);
        analytics.setRecommendations(recommendations);
        analytics.setTrendDirection("STABLE"); // 风险评估默认为稳定
        analytics.setStatus("COMPLETED");
        analytics.setIsRead(false);
        analytics.setAnalysisVersion("1.0");
        analytics.setDataSource("ASSESSMENT");
        
        try {
            analytics.setAnalysisData(objectMapper.writeValueAsString(analysisData));
            analytics.setAbnormalIndicators(String.join(", ", riskFactors));
        } catch (JsonProcessingException e) {
            log.error("序列化分析数据失败", e);
            throw new RuntimeException("序列化分析数据失败");
        }
        
        // 保存分析结果
        save(analytics);
        
        log.info("风险评估分析完成，分析ID: {}", analytics.getId());
        return analytics;
    }

    @Override
    @Transactional
    public HealthAnalytics generateSymptomPatternAnalysis(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("生成症状模式分析，用户ID: {}", userId);
        
        // 获取症状数据（这里假设从健康记录中获取症状信息）
        List<HealthRecord> healthRecords = healthRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        
        if (healthRecords.isEmpty()) {
            throw new RuntimeException("指定时间范围内没有症状数据");
        }
        
        // 分析症状模式
        Map<String, Object> analysisData = analyzeSymptomPatterns(healthRecords);
        
        // 计算症状严重程度评分
        Integer healthScore = calculateSymptomScore(analysisData);
        
        // 评估症状风险
        String riskLevel = assessSymptomRisk(analysisData, healthScore);
        
        // 生成分析摘要
        String summary = generateSymptomSummary(analysisData, healthScore, riskLevel);
        
        // 生成症状管理建议
        String recommendations = generateSymptomRecommendations(analysisData, riskLevel);
        
        // 识别症状模式
        List<String> symptomPatterns = identifySymptomPatterns(analysisData);
        
        // 分析症状趋势
        String trendDirection = analyzeSymptomTrend(healthRecords);
        
        // 创建分析记录
        HealthAnalytics analytics = new HealthAnalytics();
        analytics.setUserId(userId);
        analytics.setAnalysisType("SYMPTOM_PATTERN");
        analytics.setStartDate(startDate);
        analytics.setEndDate(endDate);
        analytics.setHealthScore(healthScore);
        analytics.setRiskLevel(riskLevel);
        analytics.setSummary(summary);
        analytics.setRecommendations(recommendations);
        analytics.setTrendDirection(trendDirection);
        analytics.setStatus("COMPLETED");
        analytics.setIsRead(false);
        analytics.setAnalysisVersion("1.0");
        analytics.setDataSource("MANUAL");
        
        try {
            analytics.setAnalysisData(objectMapper.writeValueAsString(analysisData));
            analytics.setKeyChanges(String.join(", ", symptomPatterns));
        } catch (JsonProcessingException e) {
            log.error("序列化分析数据失败", e);
            throw new RuntimeException("序列化分析数据失败");
        }
        
        // 保存分析结果
        save(analytics);
        
        log.info("症状模式分析完成，分析ID: {}", analytics.getId());
        return analytics;
    }

    @Override
    public IPage<HealthAnalytics> getAnalyticsByUserId(Long userId, Integer pageNum, Integer pageSize) {
        Page<HealthAnalytics> page = new Page<>(pageNum, pageSize);
        return healthAnalyticsMapper.selectPageByUserId(page, userId);
    }

    @Override
    public List<HealthAnalytics> getAnalyticsByType(Long userId, String analysisType) {
        return healthAnalyticsMapper.selectByUserIdAndType(userId, analysisType);
    }

    @Override
    public List<HealthAnalytics> getRecentAnalytics(Long userId, Integer limit) {
        return healthAnalyticsMapper.selectRecentByUserId(userId, limit);
    }

    @Override
    public List<Map<String, Object>> getHealthScoreTrend(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        return healthAnalyticsMapper.getHealthScoreTrend(userId, startDate, endDate);
    }

    @Override
    @Cacheable(value = "healthStats", key = "'user_' + #userId")
    public Map<String, Object> getHealthStatistics(Long userId) {
        Map<String, Object> statistics = new HashMap<>();
        
        // 统计各类型分析数量
        List<Map<String, Object>> typeStats = healthAnalyticsMapper.countByAnalysisType(userId);
        statistics.put("analysisTypeStats", typeStats);
        
        // 统计各风险等级数量
        List<Map<String, Object>> riskStats = healthAnalyticsMapper.countByRiskLevel(userId);
        statistics.put("riskLevelStats", riskStats);
        
        // 获取最新分析记录
        List<HealthAnalytics> recentAnalytics = getRecentAnalytics(userId, 5);
        statistics.put("recentAnalytics", recentAnalytics);
        
        // 计算平均健康评分
        OptionalDouble avgScore = recentAnalytics.stream()
                .filter(a -> a.getHealthScore() != null)
                .mapToInt(HealthAnalytics::getHealthScore)
                .average();
        statistics.put("averageHealthScore", avgScore.orElse(0.0));
        
        return statistics;
    }

    @Override
    public List<HealthAnalytics> getUnreadHighRiskAnalytics(Long userId) {
        return healthAnalyticsMapper.selectUnreadHighRisk(userId);
    }

    @Override
    @Transactional
    public boolean markAsRead(Long analyticsId) {
        HealthAnalytics analytics = getById(analyticsId);
        if (analytics != null) {
            analytics.setIsRead(true);
            return updateById(analytics);
        }
        return false;
    }

    @Override
    @Transactional
    public boolean batchMarkAsRead(List<Long> analyticsIds) {
        if (analyticsIds == null || analyticsIds.isEmpty()) {
            return false;
        }
        
        String ids = analyticsIds.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        
        return healthAnalyticsMapper.batchMarkAsRead(ids) > 0;
    }

    @Override
    @Transactional
    public boolean deleteAnalytics(Long analyticsId, Long userId) {
        HealthAnalytics analytics = getById(analyticsId);
        if (analytics != null && analytics.getUserId().equals(userId)) {
            return removeById(analyticsId);
        }
        return false;
    }

    @Override
    public List<HealthAnalytics> getLatestAnalyticsByType(Long userId) {
        return healthAnalyticsMapper.selectLatestByType(userId);
    }

    @Override
    @Cacheable(value = "healthStats", key = "#userId + '_monthly_' + #year + '_' + #month")
    public Map<String, Object> getMonthlySummary(Long userId, Integer year, Integer month) {
        List<Map<String, Object>> monthlySummary = healthAnalyticsMapper.getMonthlySummary(userId, year, month);
        
        Map<String, Object> result = new HashMap<>();
        result.put("year", year);
        result.put("month", month);
        result.put("summary", monthlySummary);
        
        // 计算月度总体评分
        OptionalDouble avgScore = monthlySummary.stream()
                .filter(s -> s.get("avg_score") != null)
                .mapToDouble(s -> ((Number) s.get("avg_score")).doubleValue())
                .average();
        result.put("monthlyAverageScore", avgScore.orElse(0.0));
        
        return result;
    }

    @Override
    @Cacheable(value = "trendAnalysis", key = "#userId + '_trend_' + #startDate + '_' + #endDate")
    public Map<String, Object> getImprovementTrend(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        List<Map<String, Object>> trendData = healthAnalyticsMapper.getImprovementTrend(userId, startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        result.put("trendData", trendData);
        result.put("startDate", startDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        result.put("endDate", endDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        
        // 计算改善比例
        long improvingCount = trendData.stream()
                .filter(t -> "IMPROVING".equals(t.get("trend_direction")))
                .mapToLong(t -> ((Number) t.get("count")).longValue())
                .sum();
        
        long totalCount = trendData.stream()
                .mapToLong(t -> ((Number) t.get("count")).longValue())
                .sum();
        
        double improvementRate = totalCount > 0 ? (double) improvingCount / totalCount * 100 : 0;
        result.put("improvementRate", improvementRate);
        
        return result;
    }

    @Override
    public Integer calculateHealthScore(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        // 获取用户在指定时间范围内的健康数据
        List<VitalSigns> vitalSignsList = vitalSignsMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
        
        if (vitalSignsList.isEmpty()) {
            return 50; // 默认评分
        }
        
        return calculateVitalSignsScore(vitalSignsList);
    }

    @Override
    public String assessRiskLevel(Long userId, Integer healthScore, Map<String, Object> analysisData) {
        if (healthScore >= 80) {
            return "LOW";
        } else if (healthScore >= 60) {
            return "MEDIUM";
        } else if (healthScore >= 40) {
            return "HIGH";
        } else {
            return "CRITICAL";
        }
    }

    @Override
    public String generateRecommendations(Long userId, String analysisType, Map<String, Object> analysisData, String riskLevel) {
        StringBuilder recommendations = new StringBuilder();
        
        switch (riskLevel) {
            case "LOW":
                recommendations.append("您的健康状况良好，建议继续保持现有的健康习惯。");
                break;
            case "MEDIUM":
                recommendations.append("您的健康状况需要关注，建议定期监测相关指标。");
                break;
            case "HIGH":
                recommendations.append("您的健康状况存在风险，建议尽快咨询医生。");
                break;
            case "CRITICAL":
                recommendations.append("您的健康状况需要立即关注，请立即就医。");
                break;
        }
        
        return recommendations.toString();
    }

    @Override
    public List<String> detectAbnormalIndicators(Long userId, Map<String, Object> analysisData) {
        List<String> abnormalIndicators = new ArrayList<>();
        
        // 这里可以根据具体的分析数据检测异常指标
        // 示例实现
        if (analysisData.containsKey("bloodPressure")) {
            Map<String, Object> bp = (Map<String, Object>) analysisData.get("bloodPressure");
            if (bp.containsKey("systolic") && ((Number) bp.get("systolic")).intValue() > 140) {
                abnormalIndicators.add("收缩压偏高");
            }
        }
        
        return abnormalIndicators;
    }

    @Override
    public String analyzeTrendDirection(Long userId, String analysisType, Map<String, Object> currentData, List<Map<String, Object>> historicalData) {
        // 简单的趋势分析实现
        if (historicalData.size() < 2) {
            return "STABLE";
        }
        
        // 这里可以实现更复杂的趋势分析算法
        return "STABLE";
    }

    @Override
    @Cacheable(value = "systemStats", key = "'system_health_stats'")
    public Map<String, Object> getSystemHealthStats() {
        return healthAnalyticsMapper.getSystemHealthStats();
    }

    @Override
    @Transactional
    @CacheEvict(value = {"healthAnalysis", "healthStats", "vitalSigns", "trendAnalysis", "systemStats"}, allEntries = true)
    public int cleanupExpiredRecords(Integer daysToKeep) {
        LocalDateTime cutoffDate = LocalDateTime.now().minusDays(daysToKeep);
        
        // 清理分析优化器的缓存
        analysisOptimizer.clearExpiredCache();
        
        return healthAnalyticsMapper.deleteExpiredRecords(cutoffDate);
    }

    @Override
    public String exportHealthReport(Long userId, LocalDateTime startDate, LocalDateTime endDate, String format) {
        // TODO: 实现健康报告导出功能
        throw new UnsupportedOperationException("健康报告导出功能待实现");
    }

    @Override
    public Map<String, Object> predictHealthTrend(Long userId, String analysisType, Integer days) {
        // TODO: 实现健康趋势预测功能
        throw new UnsupportedOperationException("健康趋势预测功能待实现");
    }

    @Override
    public Map<String, Object> compareWithPeers(Long userId) {
        // TODO: 实现与同龄人群比较功能
        throw new UnsupportedOperationException("同龄人群比较功能待实现");
    }

    @Override
    public List<Map<String, Object>> generateHealthGoals(Long userId, Map<String, Object> analysisData) {
        // TODO: 实现个性化健康目标生成功能
        throw new UnsupportedOperationException("个性化健康目标生成功能待实现");
    }

    // 私有辅助方法

    private Map<String, Object> analyzeVitalSigns(List<VitalSigns> vitalSignsList) {
        Map<String, Object> analysis = new HashMap<>();
        
        if (vitalSignsList.isEmpty()) {
            return analysis;
        }
        
        // 计算平均值
        OptionalDouble avgSystolic = vitalSignsList.stream()
                .filter(vs -> vs.getSystolicBp() != null)
                .mapToDouble(vs -> vs.getSystolicBp().doubleValue())
                .average();
        
        OptionalDouble avgDiastolic = vitalSignsList.stream()
                .filter(vs -> vs.getDiastolicBp() != null)
                .mapToDouble(vs -> vs.getDiastolicBp().doubleValue())
                .average();
        
        // VitalSigns实体类中没有心率字段，使用默认值
        OptionalDouble avgHeartRate = OptionalDouble.of(75.0);
        
        analysis.put("avgSystolicPressure", avgSystolic.orElse(0));
        analysis.put("avgDiastolicPressure", avgDiastolic.orElse(0));
        analysis.put("avgHeartRate", avgHeartRate.orElse(0));
        analysis.put("recordCount", vitalSignsList.size());
        
        return analysis;
    }

    private Integer calculateVitalSignsScore(List<VitalSigns> vitalSignsList) {
        if (vitalSignsList.isEmpty()) {
            return 50;
        }
        
        int totalScore = 0;
        int count = 0;
        
        for (VitalSigns vs : vitalSignsList) {
            int score = 100;
            
            // 血压评分
            if (vs.getSystolicBp() != null && vs.getDiastolicBp() != null) {
                if (vs.getSystolicBp() > 140 || vs.getDiastolicBp() > 90) {
                    score -= 20;
                } else if (vs.getSystolicBp() > 130 || vs.getDiastolicBp() > 85) {
                    score -= 10;
                }
            }
            
            // 心率评分
            if (vs.getHeartRate() != null) {
                if (vs.getHeartRate() > 100 || vs.getHeartRate() < 60) {
                    score -= 15;
                }
            }
            
            totalScore += score;
            count++;
        }
        
        return count > 0 ? totalScore / count : 50;
    }

    private String assessVitalSignsRisk(Map<String, Object> analysisData, Integer healthScore) {
        if (healthScore >= 80) {
            return "LOW";
        } else if (healthScore >= 60) {
            return "MEDIUM";
        } else if (healthScore >= 40) {
            return "HIGH";
        } else {
            return "CRITICAL";
        }
    }

    private String generateVitalSignsSummary(Map<String, Object> analysisData, Integer healthScore, String riskLevel) {
        return String.format("生命体征分析完成，健康评分：%d分，风险等级：%s。", healthScore, riskLevel);
    }

    private String generateVitalSignsRecommendations(Map<String, Object> analysisData, String riskLevel) {
        switch (riskLevel) {
            case "LOW":
                return "您的生命体征正常，建议继续保持健康的生活方式。";
            case "MEDIUM":
                return "您的生命体征需要关注，建议定期监测血压和心率。";
            case "HIGH":
                return "您的生命体征存在异常，建议尽快咨询医生。";
            case "CRITICAL":
                return "您的生命体征异常严重，请立即就医。";
            default:
                return "请继续关注您的健康状况。";
        }
    }

    private List<String> detectVitalSignsAbnormalities(List<VitalSigns> vitalSignsList) {
        List<String> abnormalities = new ArrayList<>();
        
        for (VitalSigns vs : vitalSignsList) {
            if (vs.getSystolicBp() != null && vs.getSystolicBp() > 140) {
                abnormalities.add("收缩压偏高");
            }
            if (vs.getDiastolicBp() != null && vs.getDiastolicBp() > 90) {
                abnormalities.add("舒张压偏高");
            }
            if (vs.getHeartRate() != null && (vs.getHeartRate() > 100 || vs.getHeartRate() < 60)) {
                abnormalities.add("心率异常");
            }
        }
        
        return abnormalities.stream().distinct().collect(Collectors.toList());
    }

    private String analyzeVitalSignsTrend(List<VitalSigns> vitalSignsList) {
        if (vitalSignsList.size() < 2) {
            return "STABLE";
        }
        
        // 简单的趋势分析
        VitalSigns first = vitalSignsList.get(0);
        VitalSigns last = vitalSignsList.get(vitalSignsList.size() - 1);
        
        if (first.getSystolicBp() != null && last.getSystolicBp() != null) {
            if (last.getSystolicBp() < first.getSystolicBp() - 5) {
                return "IMPROVING";
            } else if (last.getSystolicBp() > first.getSystolicBp() + 5) {
                return "DECLINING";
            }
        }
        
        return "STABLE";
    }

    // 其他分析方法的简化实现
    private Map<String, Object> analyzeHealthTrend(List<HealthRecord> healthRecords, List<VitalSigns> vitalSignsList) {
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("healthRecordCount", healthRecords.size());
        analysis.put("vitalSignsCount", vitalSignsList.size());
        return analysis;
    }

    private Integer calculateTrendScore(Map<String, Object> analysisData) {
        return 75; // 简化实现
    }

    private String assessTrendRisk(Map<String, Object> analysisData, Integer healthScore) {
        return assessRiskLevel(null, healthScore, analysisData);
    }

    private String generateTrendSummary(Map<String, Object> analysisData, Integer healthScore, String riskLevel) {
        return String.format("健康趋势分析完成，健康评分：%d分，风险等级：%s。", healthScore, riskLevel);
    }

    private String generateTrendRecommendations(Map<String, Object> analysisData, String riskLevel) {
        return generateRecommendations(null, "HEALTH_TREND", analysisData, riskLevel);
    }

    private String analyzeTrendDirection(Map<String, Object> analysisData) {
        return "STABLE"; // 简化实现
    }

    private Map<String, Object> performRiskAssessment(Long userId, List<HealthRecord> healthRecords, List<VitalSigns> vitalSignsList) {
        Map<String, Object> assessment = new HashMap<>();
        assessment.put("riskFactors", new ArrayList<>());
        assessment.put("protectiveFactors", new ArrayList<>());
        return assessment;
    }

    private Integer calculateRiskScore(Map<String, Object> analysisData) {
        return 70; // 简化实现
    }

    private String determineRiskLevel(Integer healthScore, Map<String, Object> analysisData) {
        return assessRiskLevel(null, healthScore, analysisData);
    }

    private String generateRiskSummary(Map<String, Object> analysisData, Integer healthScore, String riskLevel) {
        return String.format("风险评估完成，健康评分：%d分，风险等级：%s。", healthScore, riskLevel);
    }

    private String generateRiskRecommendations(Map<String, Object> analysisData, String riskLevel) {
        return generateRecommendations(null, "RISK_ASSESSMENT", analysisData, riskLevel);
    }

    private List<String> identifyRiskFactors(Map<String, Object> analysisData) {
        return new ArrayList<>(); // 简化实现
    }

    private Map<String, Object> analyzeSymptomPatterns(List<HealthRecord> healthRecords) {
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("symptomCount", healthRecords.size());
        return analysis;
    }

    private Integer calculateSymptomScore(Map<String, Object> analysisData) {
        return 65; // 简化实现
    }

    private String assessSymptomRisk(Map<String, Object> analysisData, Integer healthScore) {
        return assessRiskLevel(null, healthScore, analysisData);
    }

    private String generateSymptomSummary(Map<String, Object> analysisData, Integer healthScore, String riskLevel) {
        return String.format("症状模式分析完成，健康评分：%d分，风险等级：%s。", healthScore, riskLevel);
    }

    private String generateSymptomRecommendations(Map<String, Object> analysisData, String riskLevel) {
        return generateRecommendations(null, "SYMPTOM_PATTERN", analysisData, riskLevel);
    }

    private List<String> identifySymptomPatterns(Map<String, Object> analysisData) {
        return new ArrayList<>(); // 简化实现
    }

    private String analyzeSymptomTrend(List<HealthRecord> healthRecords) {
        return "STABLE"; // 简化实现
    }

    /**
     * 生成综合健康分析
     *
     * @param userId    用户ID
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 综合分析结果
     */
    @Transactional
    public HealthAnalytics generateComprehensiveAnalysis(Long userId, LocalDateTime startDate, LocalDateTime endDate) {
        log.info("生成综合健康分析，用户ID: {}", userId);
        
        try {
            // 获取所有相关数据
            List<HealthRecord> healthRecords = healthRecordMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
            List<VitalSigns> vitalSignsList = vitalSignsMapper.selectByUserIdAndDateRange(userId, startDate, endDate);
            
            // 综合分析数据
            Map<String, Object> analysisData = new HashMap<>();
            
            // 生命体征分析
            if (!vitalSignsList.isEmpty()) {
                Map<String, Object> vitalAnalysis = analysisOptimizer.optimizedVitalSignsAnalysis(vitalSignsList);
                analysisData.put("vitalSigns", vitalAnalysis);
            }
            
            // 健康趋势分析
            Map<String, Object> trendAnalysis = analyzeHealthTrend(healthRecords, vitalSignsList);
            analysisData.put("healthTrend", trendAnalysis);
            
            // 风险评估
            Map<String, Object> riskAssessment = performRiskAssessment(userId, healthRecords, vitalSignsList);
            analysisData.put("riskAssessment", riskAssessment);
            
            // 症状模式分析
            if (!healthRecords.isEmpty()) {
                Map<String, Object> symptomAnalysis = analyzeSymptomPatterns(healthRecords);
                analysisData.put("symptomPattern", symptomAnalysis);
            }
            
            // 计算综合健康评分
            Integer healthScore = calculateComprehensiveScore(analysisData, vitalSignsList, healthRecords);
            
            // 评估综合风险等级
            String riskLevel = assessComprehensiveRisk(analysisData, healthScore);
            
            // 生成综合分析摘要
            String summary = generateComprehensiveSummary(analysisData, healthScore, riskLevel);
            
            // 生成综合建议
            String recommendations = generateComprehensiveRecommendations(analysisData, riskLevel);
            
            // 分析整体趋势
            String trendDirection = analyzeComprehensiveTrend(analysisData);
            
            // 创建综合分析记录
            HealthAnalytics analytics = new HealthAnalytics();
            analytics.setUserId(userId);
            analytics.setAnalysisType("COMPREHENSIVE");
            analytics.setStartDate(startDate);
            analytics.setEndDate(endDate);
            analytics.setHealthScore(healthScore);
            analytics.setRiskLevel(riskLevel);
            analytics.setSummary(summary);
            analytics.setRecommendations(recommendations);
            analytics.setTrendDirection(trendDirection);
            analytics.setStatus("COMPLETED");
            analytics.setIsRead(false);
            analytics.setAnalysisVersion("1.0");
            analytics.setDataSource("COMPREHENSIVE");
            
            try {
                analytics.setAnalysisData(objectMapper.writeValueAsString(analysisData));
            } catch (JsonProcessingException e) {
                log.error("序列化综合分析数据失败", e);
                throw new RuntimeException("序列化综合分析数据失败");
            }
            
            // 保存分析结果
            save(analytics);
            
            log.info("综合健康分析完成，分析ID: {}", analytics.getId());
            return analytics;
            
        } catch (Exception e) {
            log.error("生成综合健康分析失败", e);
            throw new RuntimeException("生成综合健康分析失败: " + e.getMessage());
        }
    }
    
    private Integer calculateComprehensiveScore(Map<String, Object> analysisData, List<VitalSigns> vitalSignsList, List<HealthRecord> healthRecords) {
        int totalScore = 0;
        int componentCount = 0;
        
        // 生命体征评分
        if (!vitalSignsList.isEmpty()) {
            totalScore += calculateVitalSignsScore(vitalSignsList);
            componentCount++;
        }
        
        // 健康趋势评分
        totalScore += calculateTrendScore(analysisData);
        componentCount++;
        
        // 风险评估评分
        totalScore += calculateRiskScore(analysisData);
        componentCount++;
        
        // 症状模式评分
        if (!healthRecords.isEmpty()) {
            totalScore += calculateSymptomScore(analysisData);
            componentCount++;
        }
        
        return componentCount > 0 ? totalScore / componentCount : 70;
    }
    
    private String assessComprehensiveRisk(Map<String, Object> analysisData, Integer healthScore) {
        if (healthScore >= 85) {
            return "LOW";
        } else if (healthScore >= 70) {
            return "MEDIUM";
        } else if (healthScore >= 50) {
            return "HIGH";
        } else {
            return "CRITICAL";
        }
    }
    
    private String generateComprehensiveSummary(Map<String, Object> analysisData, Integer healthScore, String riskLevel) {
        return String.format("综合健康分析完成。您的整体健康评分为%d分，风险等级为%s。分析涵盖了生命体征、健康趋势、风险评估和症状模式等多个维度。", 
                healthScore, riskLevel);
    }
    
    private String generateComprehensiveRecommendations(Map<String, Object> analysisData, String riskLevel) {
        StringBuilder recommendations = new StringBuilder();
        
        switch (riskLevel) {
            case "LOW":
                recommendations.append("您的整体健康状况良好。建议：1) 继续保持健康的生活方式；2) 定期进行健康检查；3) 保持适量运动和均衡饮食。");
                break;
            case "MEDIUM":
                recommendations.append("您的健康状况需要适度关注。建议：1) 加强健康监测；2) 调整生活方式；3) 定期咨询医生；4) 注意压力管理。");
                break;
            case "HIGH":
                recommendations.append("您的健康状况存在较高风险。建议：1) 尽快咨询专业医生；2) 严格遵循医嘱；3) 密切监测健康指标；4) 调整饮食和运动计划。");
                break;
            case "CRITICAL":
                recommendations.append("您的健康状况需要紧急关注。建议：1) 立即就医；2) 严格按医嘱治疗；3) 持续监测关键指标；4) 家人陪同就诊。");
                break;
            default:
                recommendations.append("请继续关注您的健康状况，定期进行健康检查。");
        }
        
        return recommendations.toString();
    }
    
    private String analyzeComprehensiveTrend(Map<String, Object> analysisData) {
        // 简化的综合趋势分析
        return "STABLE";
    }
    
}